Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
Switch case not working with URLs [JavaScript]

I'm trying to use a switch statement:

var currentURL = window.location.href;
switch(currentURL)
{
  // Home page
  case "http://localhost/myWebsitePath/":
    alert("Home!");
    break;
  // Blog home page
  case "http://localhost/myWebsitePath/blog/":
    alert("Blog!");
    break;
}

When visiting http://localhost/myWebsitePath/, I get the alert. When visiting http://localhost/myWebsitePath/blog/, I don't always get the alert. It seems to sometimes work when clicking a hyperlink from home page. Do I need to escape any special characters to guarantee it works?

Note: both paths have their respective index.html files in the folders

console.log(currentURL);
console.log(typeof(currentURL));

Produces:

http://localhost/myWebsitePath/blog/ string

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Seems to now work correctly if I use:

var currentURL = window.location.href;
currentURL = encodeURIComponent(currentURL);

Then switch case as follows:

switch(currentURL)
{
  // Home page
  case "http%3A%2F%2Flocalhost%2FmyWebsitePath%2F":
    alert("Home!");
    break;
  // Blog home page
  case "http%3A%2F%2Flocalhost%2FmyWebsitePath%2Fblog%2F":
    alert("Blog!");
    break;
}

I used https://meyerweb.com/eric/tools/dencoder/ to encode/decode the URLs initially and insert those into my switch cases.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda